/*
 * @Description:
 * @Version: 1.0
 * @Author: yxx
 * @Date: 2023-09-21 10:02:20
 * @LastEditors: yxx
 * @LastEditTime: 2025-05-14 10:10:10
 */
// import md5 from "md5";
import { Md5 } from "ts-md5"
let appId = "8200"
let appKey = "a3e4baf01fee4385b9a23f7c97e97biz"

export { appKey }

/**获取字符串中特殊符号存在的个数 */
function sum(str: string, a: string) {
  let b = str.indexOf(a)
  let num = 0
  while (b !== -1) {
    num++
    b = str.indexOf(a, b + 1)
  }
  return num
}

/**将get参数转为对象 */
function sumObj(str: string, a: string) {
  let num = sum(str, a)
  // debugger;
  let obj: any = {}
  if (num === 0) {
    obj[str.split("=")[0]] = str.split("=")[1]
  } else {
    for (let i = 0; i <= num; i++) {
      obj[str.split(a)[i].split("=")[0]] = str.split(a)[i].split("=")[1]
    }
  }
  return obj
}
/**拼接signstr */
function connectStr(params: any, signStr: string, paramsTrim: any) {
  let paramSort = Object.keys(params).sort()
  let sp = ""
  for (let i = 0; i < paramSort.length; i++) {
    let value = params[paramSort[i]]
    if (value == undefined || value == null || typeof value === "object") {
      continue
    }
    // 针对数组
    // const fmtValue = Array.isArray(value) ? JSON.stringify(value) : value;
    // 针对json对象，格式化后无法实现与后端数据一致
    // const fmtValue = (typeof value == "object") ? JSON.stringify(value) : value;
    signStr += sp + paramSort[i] + "=" + value
    sp = "&"
    paramsTrim[paramSort[i]] = params[paramSort[i]]
  }
  return [signStr, paramsTrim]
}
export function buildSign(config: any) {
  let paramsTrim: any = {}
  let timestamp = Math.round(new Date().getTime() / 1000)
  let signStr = appId + appKey + timestamp
  // 判断是否是get并且拼接参数
  if (config.url.indexOf("?") > -1 && (config.method == "GET" || config.method == "get")) {
    let obj: any = sumObj(config.url.split("?")[1], "&")
    if (obj) {
      signStr = connectStr(obj, signStr, paramsTrim)[0]
      paramsTrim = connectStr(obj, signStr, paramsTrim)[1]
    }
  } else {
    if (config.data) {
      signStr = connectStr(config.data, signStr, paramsTrim)[0]
      paramsTrim = connectStr(config.data, signStr, paramsTrim)[1]
    }
  }
  paramsTrim.sign = Md5.hashStr(signStr)
  config.url += "?appId=" + appId + "&timestamp=" + timestamp + "&sign=" + paramsTrim.sign
  // console.log(config.url, "1234");
  // GET请求参数赋值
  if (config.method == "GET" || config.method == "get") {
    // 对get请求方式并且有参数的情况进行处理将后面？替换成&
    if (sum(config.url, "?") > 1) {
      config.url =
        config.url.split("?")[0] +
        "?" +
        config.url.split("?")[1] +
        "&appId=" +
        appId +
        "&timestamp=" +
        timestamp +
        "&sign=" +
        paramsTrim.sign
    }
  }
}
